<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%@ include file="loginDetails.jsp" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<HTML>
<BODY>

<%!
boolean CheckUniqueAndRegister(JspWriter out,HttpServletRequest request,
					HttpSession session)
{
        String username = request.getParameter("username");
	String password = request.getParameter("password");
	String retStr = null;
	String hashedPassword = null;
	String salt = null;
        
	int insertId = -1;
	int userId = -1;
        
        
	if(username == null || password == null)
		return false;
        
	if((username.length() == 0) || (password.length() == 0))
		return false;
        
        
	// Should make a database connection here and check password
	try { // Load driver class
		Class.forName("com.mysql.jdbc.Driver");
	}
	catch (java.lang.ClassNotFoundException e) {
		System.err.println("ClassNotFoundException: " +e);
	}
	//Check if username already exists. If it does then just return to login page
	Connection con = null;
	try { 
		con = DriverManager.getConnection(url+db, uid, pwd); 
		Statement stmt = con.createStatement();
		ResultSet rst = stmt.executeQuery("SELECT UserId FROM User WHERE Username = '" + username + "'");

		while (rst.next()){ 
			hashedPassword = rst.getString("HashedPW");
			salt = rst.getString("Salt");
			userId = rst.getInt("UserId");
		}
		con.close();
	}
	catch (SQLException ex) { System.err.println(ex); }
	finally{ 
		if (con != null)
		try
		{ 
                    con.close(); // Let's close the connection once we're done using it, shall we? 
                }
		catch (SQLException ex) 
                { 
                    System.err.println(ex); 
                }
	} 
	if(userId >= 0){
		return false;
	}
	
	//register the new user and log them in
	con = null;
	try { 
		con = DriverManager.getConnection(url+db, uid, pwd); 
		
                
                PreparedStatement insertStatement = con.prepareStatement("INSERT INTO User (Username, HashedPW, Salt) VALUES (?, ?, ?)");
		
                String pwsalt = getSalt();
                
                insertStatement.setString(1, username);
                insertStatement.setString(2, md5(password+pwsalt));
                insertStatement.setString(3, pwsalt);

                if(insertStatement.execute()) {
                    ResultSet rst = con.createStatement().executeQuery("SELECT LAST_INSERT_ID()");
                    insertId = rst.getInt(0);
                } else {
                    // There was an error inserting the new user
                }
                
		con.close();
	}
	catch (SQLException ex) { System.err.println(ex); }
	finally{ 
		if (con != null)
		try
		{ con.close(); }
		catch (SQLException ex) { System.err.println(ex); }
	} 
	
	if(insertId > 0){
		session.setAttribute("Username", username);
		session.setAttribute("UserId", insertId);
		return true;
	}
	else{
		return false;
	}
} 
%>


<%
boolean authenticatedUser = false;
session = request.getSession(true);// May create new session
//try{
	authenticatedUser = CheckUniqueAndRegister(out,request,session);
//}
//catch(IOException e){ System.err.println(e); }

if(!authenticatedUser)
	response.sendRedirect("index.jsp"); // Success
else
	response.sendRedirect("Home.jsp"); // Failed login
// Redirect back to login page with a message
%>

</BODY>
</HTML>